<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/uploadexcel/index')"
            >excel导入</el-button
          >
          <el-button type="danger" size="small" @click="getEmpTotalList"
            >excel导出</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="centerDialogVisible = true"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            :index="indexChange"
            width="50px"
          />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto" width="100">
            <template #default="{ row }">
              <img
                :src="row.staffPhoto || defaultImg"
                alt=""
                style="width: 80px; height: 80px"
              />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formType"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{ row }">
              {{ dateFomatter(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employess/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="del(row.id, row.username)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            style="text-align: center"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>

      <el-dialog
        title="编辑员工"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
      >
        <el-form
          ref="form"
          :model="form"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="姓名">
            <el-input
              v-model="dialogForm.username"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机">
            <el-input
              v-model="dialogForm.mobile"
              placeholder="请输入手机"
            ></el-input>
          </el-form-item>
          <el-form-item label="入职时间：">
            <div class="block">
              <el-date-picker
                v-model="dialogForm.timeOfEntry"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="聘用形式：">
            <el-select
              v-model="dialogForm.formOfEmployment"
              placeholder="请选择聘用形式"
            >
              <el-option label="正式" :value="1"></el-option>
              <el-option label="非正式" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工号：">
            <el-input
              v-model="dialogForm.workNumber"
              placeholder="请输入工号"
            ></el-input>
          </el-form-item>
          <el-form-item label="部门：">
            <el-select
              v-model="dialogForm.departmentName"
              placeholder="请选择部门"
            >
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="转正时间：">
            <div class="block">
              <el-date-picker
                v-model="dialogForm.correcionTime"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="centerDialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmpListAPI, delEmpAPI, addEmpAPI } from '@/api/employees'
import dayjs from 'dayjs'
import { getdepartmentListAPI } from '@/api/departments'
import empEmun from '@/constant/employees'

export default {
  name: 'Employees',
  data () {
    return {
      defaultImg: require('@/assets/common/bigUserHeader.png'),
      total: 0, //总条目数
      form: {
        page: 1,
        size: 2
      },
      dialogForm: {
        username: undefined,
        mobile: undefined,
        timeOfEntry: dayjs(new Date()).format('YYYY-MM-DD'),
        formOfEmployment: 1,
        workNumber: undefined,
        departmentName: undefined,
        correcionTime: dayjs(new Date()).format('YYYY-MM-DD')
      },
      list: [],
      departmentList: [],
      centerDialogVisible: false,
      headersArr: [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
    }
  },
  methods: {
    /**
     * 导出文档数据
     */
    handleDownload (arrys) {
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: this.headersArr,
          data: arrys,
          filename: '员工信息',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    /**
     * 格式化数据
     */
    arrObjFomatter (arrObj) {
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const arr = []
      arrObj.forEach(item => {
        const value = []
        this.headersArr.forEach(key => {
          const header = headersRelations[key]
          let val = item[header]
          if (header === 'formOfEmployment') {
            const flag = empEmun.hireType.find(item => item.id === +val)
            val = flag ? flag.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(header)) {
            val = this.dateFomatter(val)
          }
          value.push(val)
        })
        arr.push(value)
      })
      this.handleDownload(arr)
    },
    /**
     * 请求获取员工所有数据信息
     */
    async getEmpTotalList () {
      const {
        data: { data }
      } = await getEmpListAPI({ page: 1, size: this.total })
      this.arrObjFomatter(data.rows)
    },
    /**
     * 获取部门信息
     */
    async getdepartmentlist () {
      const {
        data: { data }
      } = await getdepartmentListAPI()
      this.departmentList = data.depts
    },

    /**
     * 添加员工信息
     */
    async onSubmit () {
      await addEmpAPI(this.dialogForm)
      this.centerDialogVisible = false
    },
    /**
     * 格式化时间函数
     */
    dateFomatter (date) {
      return date ? dayjs(date).format('YYYY-MM-DD') : ''
    },
    /**
     * 删除用户
     */
    del (id, username) {
      this.$confirm(`您确定需要删除：${username}`, '提示信息')
        .then(async () => {
          await delEmpAPI(id)
          this.$message.success(`已成功删除用户:${username}`)
          this.getEmplist()
        })
        .catch(() => {})
    },
    /**
     * 入职方式格式处理
     */
    formType (cellvalue) {
      return +cellvalue.formOfEmployment === 1 ? '正式' : '非正式'
    },
    /**
     * 当前页码发生变化
     */
    handleCurrentChange (val) {
      this.form.page = val
      this.getEmplist()
    },
    /**
     * 最大显示条目数
     */
    handleSizeChange (val) {
      this.form.size = val
      this.getEmplist()
    },

    /**
     * 序号规整化
     */
    indexChange (index) {
      return this.form.size * (this.form.page - 1) + index + 1
    },
    /**
     * 获取员工列表
     */
    async getEmplist () {
      const { data: res } = await getEmpListAPI(this.form)
      this.total = res.data.total
      this.list = res.data.rows
    }
  },
  created () {
    this.getEmplist()
    this.getdepartmentlist()
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  background-color: #409eff;
  text-align: left;
  span {
    color: #fff;
  }
  i {
    color: #fff;
  }
}
</style>
